from rest_framework import serializers
from connection.models import Connection, Certificate
from connection.services import connection_service
from connection.serializers.partner import PartnerSerializer


class ConnectionSerializer(serializers.ModelSerializer):
    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['partner'] = PartnerSerializer(instance.partner).data
        our_side_certificate = connection_service.get_our_side_certificate(instance.id)
        other_side_certificate = connection_service.get_other_side_certificate(instance.id)
        data['our_side_certificate'] = CertificateSerializer(our_side_certificate).data if our_side_certificate else None
        data['other_side_certificate'] = CertificateSerializer(other_side_certificate).data if other_side_certificate else None
        return data

    class Meta:
        model = Connection
        fields = '__all__'


class ConnectionSimpleSerializer(serializers.ModelSerializer):
    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['partner'] = {
            'id': instance.partner.id,
            'name': instance.partner.name
        }
        return data

    class Meta:
        model = Connection
        fields = ['id', 'partner', 'state']


class CertificateSerializer(serializers.ModelSerializer):
    def mask(self, data):
        ''' 敏感信息没必要传递到前端
        '''
        data['data'].pop('public_key', None)
        data['data'].pop('second_key', None)
        data['data'].pop('holder_open_id', None)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        self.mask(data)
        return data

    class Meta:
        model = Certificate
        exclude = ['public_key', 'second_key', 'holder_open_id']
